<template>
  <div class="login">
    <div class="container">
      <div class="avatar">
        <img src="../assets/avatar.jpg" alt="" />
      </div>
      <div>
        <el-input v-model="user.username" placeholder="请输入账号" prefix-icon="el-icon-user-solid">
        </el-input>
        <el-input v-model="user.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-key">
        </el-input>
        <el-button class="login-btn" type="primary" @click="loginFn">登录</el-button>
      </div>
    </div>
  </div>
</template>


<script>
import {login} from '../api/user'
export default {
  data(){
    return{
      user:{
        username:'',
        password:''
      }
    }
  },
  methods:{
    loginFn(){
      //增加判断,用户名和密码不能为空
      if(!this.user.username){
        this.$message.error('用户名不能为空')
        return
      }
      if(!this.user.password){
        this.$message.error('密码不能为空')
        return
      }
      //加载效果
      //设置加载效果(全屏)的作用:
        //1.提高用户体验
        //2.避免用户反复点击登录按钮 , 造成重复请求接口问题(用'防抖' 同意可以解决这个问题)
      const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
      });
      //判断过后成功才调接口
      login(this.user).then(res=>{
        //登录成功就关闭加载
        loading.close();
        //登录成功或者失败给出提示框
        if(res.data.message == '登录成功'){
           this.$message.success(res.data.message)
        }else{
          this.$message.error(res.data.message)
        }
        //将id和token存储在本地
        localStorage.setItem('back-id',res.data.data.user.id)
        localStorage.setItem('back-token',res.data.data.token)
        //登录成功跳转到index
        this.$router.push('/layout')
      })
    }
  }
};
</script>


<style lang="less" scoped>
.login {
  position: fixed;
  width: 100%;
  height: 100%;
  background-color: #2f4050;
  .container {
    position: absolute;
    left: 0;
    right: 0;
    width: 400px;
    padding: 0px 40px 15px 40px;
    margin: 200px auto;
    background: white;
    .avatar {
      position: relative;
      left: 50%;
      width: 120px;
      height: 120px;
      margin-left: -60px;
      margin-top: -60px;
      box-sizing: border-box;
      border-radius: 50%;
      border: 10px solid #fff;
      box-shadow: 0 1px 5px #ccc;
      overflow: hidden;
    }
    .el-input{
        margin-bottom: 20px;
    }
    .login-btn {
      width: 100%;
    }
  }
}
</style>